package com.lzx.mall_tiny01.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.lzx.mall_tiny01.common.utils.JwtTokeUtil;
import com.lzx.mall_tiny01.dao.UmsAdminRoleRelationDao;
import com.lzx.mall_tiny01.mbg.mapper.UmsAdminMapper;
import com.lzx.mall_tiny01.mbg.model.UmsAdmin;
import com.lzx.mall_tiny01.mbg.model.UmsAdminExample;
import com.lzx.mall_tiny01.mbg.model.UmsPermission;
import com.lzx.mall_tiny01.service.UmsAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author: lzx
 * @Date: 2021/4/27 10:54
 */
@Slf4j
@Service
public class UmsAdminServceImpl implements UmsAdminService {
    @Autowired
    private UmsAdminMapper adminMapper;
    @Autowired
    private UmsAdminRoleRelationDao adminRoleRelationDao;
    @Autowired
    private UserDetailsService userDetailsService;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokeUtil jwtTokeUtil;

    private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    @Override
    public UmsAdmin getAdminByUsername(String username) {
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsAdmin> umsAdminList = adminMapper.selectByExample(example);
        if (CollUtil.isNotEmpty(umsAdminList)) {
            return umsAdminList.get(0);
        }
        return null;
    }

    @Override
    public List<UmsPermission> getPermissionList(Long id) {
        return adminRoleRelationDao.getPermissionList(id);
    }

    @Override
    public UmsAdmin register(UmsAdmin admin) {
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(admin.getUsername());
        long size = adminMapper.selectByExample(example).size();
        if (size > 0) {
            return null;
        }
        admin.setCreateTime(new Date());
        admin.setStatus(1);
        admin.setPassword(passwordEncoder.encode(admin.getPassword()));
        adminMapper.insert(admin);
        return admin;
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            token = jwtTokeUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            log.warn("登录异常：{}", e.getMessage());
        }
        return token;
    }
}
